package com.pig4cloud.pigx.common.security.component;

import cn.hutool.core.map.MapUtil;
import com.pig4cloud.pigx.common.security.constant.SecurityConstants;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @description: 根据checktoken的结果转化用户信息
 * @Author 兔子不吃窝边曹
 * @create 2022/8/5 14:56
 **/
@Slf4j
public class PigxUserAuthenticationConverter implements UserAuthenticationConverter {

    private static final String N_A = "N/A";

    /**
     * 提取有关要在访问令牌中使用的用户的信息（即用于资源服务器）
     *
     * @param authentication an authentication representing a user
     * @return a map of key values representing the unique information about the user
     */
    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put(USERNAME, authentication.getName());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

    /**
     * {@link #convertUserAuthentication(Authentication)}.
     * 从map中提取身份验证
     *
     * @param responseMap a map of user information
     * @return an Authentication representing the user or null if there is none
     */
    @Override
    public Authentication extractAuthentication(Map<String, ?> responseMap) {

        if (responseMap.containsKey(USERNAME)) {
            Collection<? extends GrantedAuthority> authorities = getAuthorities(responseMap);

            Map<String, ?> map = MapUtil.get(responseMap, SecurityConstants.DETAILS_USER, Map.class);
            String username = MapUtil.getStr(map, SecurityConstants.DETAILS_USERNAME);
            Long id = MapUtil.getLong(map, SecurityConstants.DETAILS_USER_ID);
            Long deptId = MapUtil.getLong(map, SecurityConstants.DETAILS_DEPT_ID);
            Long tenantId = MapUtil.getLong(map, SecurityConstants.DETAILS_TENANT_ID);
            String phone = MapUtil.getStr(map, SecurityConstants.DETAILS_PHONE);
            String nickName = MapUtil.getStr(map, SecurityConstants.NICK_NAME);
            String avatar = MapUtil.getStr(map, SecurityConstants.DETAILS_AVATAR);
            PigxUser user = new PigxUser(id, username, deptId, phone, avatar, nickName, tenantId,
                    N_A, true, true, true, true,
                    authorities);
            return new UsernamePasswordAuthenticationToken(user, N_A, authorities);
        }
        return null;
    }

    private Collection<? extends GrantedAuthority> getAuthorities(Map<String, ?> map) {
        Object authorities = map.get(AUTHORITIES);
        if (authorities instanceof String) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList((String) authorities);
        }
        if (authorities instanceof Collection) {
            return AuthorityUtils.commaSeparatedStringToAuthorityList(
                    StringUtils.collectionToCommaDelimitedString((Collection<?>) authorities));
        }
        return AuthorityUtils.NO_AUTHORITIES;
    }


}
